import React, { Component } from 'react';
import axios from 'axios';
import PubSub from 'pubsub-js';

export default class Search extends Component {
    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">Search Github Users</h3>
                <div>
                    <input ref={el => this.iptEle = el} type="text" placeholder="enter the name you search" />&nbsp;
                    <button onClick={this.search}>Search</button>
                </div>
            </section>
        )
    }

    search = () => {
        const { value } = this.iptEle;//拿到用户输入的内容
        console.log(value);

        //Search发布，第一次请求
        PubSub.publish('updateList', { items: [], isFirst: true, isLoading: false, errMsg: '' })
        /* 
          items: [],
          isFirst: true,//是否是第一次访问
          isLoading: true,//正在加载中
          errMsg: '',
        */

        //发送axios请求
        axios.get('https://api.github.com/search/users', {
            params: {
                q: value
            }
        })
            .then(res => {
                console.log(res);
                console.log(res.data.items);//拿到请求回来的对象数组
                const userdata = res.data.items;
                const task =   res.data.items.length ? 0:2
                //Search发布，成功拿到的请求数据
                PubSub.publish('updateList', { items: userdata, isFirst: false, isLoading:task, errMsg: '' })

            }) 
            .catch(reason => {
                console.log(reason);
                //Search发布，各种原因请求不到数据
                PubSub.publish('updateList', { items: [], isFirst: false, isLoading: false, errMsg: reason })
            })

    }


}
